import 'dart:async';

import 'package:flutter/material.dart';

class StreamDemo extends StatefulWidget {
  @override
  State<StreamDemo> createState() => _StreamDemoState();
}

class _StreamDemoState extends State<StreamDemo> {
  late StreamSubscription _StreamSubscription;
  StreamController<String> _streamController = StreamController();
  StreamController<String> _streamB = StreamController.broadcast();
  String _changeData = "";

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Wrap(
      children: [
        Text("数据变化之后显示到界面上 ${_changeData}"),
        Divider(),
        ElevatedButton(onPressed: onPause, child: Text("暂停")),
        ElevatedButton(onPressed: onCancel, child: Text("取消")),
        ElevatedButton(onPressed: onEnd, child: Text("恢复")),
        StreamBuilder(
          stream: _streamB.stream,
          builder: (context, snapShot) {
            var showData=snapShot.hasData?snapShot.data:"";
            return Text("我是通过StreamBuilder 监听数据变换 ${showData}");
          },
        ),
      ],
    );
  }

  @override
  void initState() {
    super.initState();

    Stream<String> _stream = Stream.fromFuture(fetchData());

    _streamController.stream.listen((ondata) {
      debugPrint("通过控制器管理 ${ondata}");
    });

    _streamB.stream.listen((ondata) {
      setState(() {
        _changeData = ondata;
      });
      debugPrint("多次订阅1 ${ondata}");
    });

    _streamB.stream.listen((ondata) {
      debugPrint("多次订阅2 ${ondata}");
    });
    _StreamSubscription = _stream.listen((ondata) {
      debugPrint("监听变化数据 ${ondata}");
    });
  }

  Future<String> fetchData() async {
    await Future.delayed(Duration(seconds: 1));
    return "hellow";
  }

  void onPause() {
    _StreamSubscription.pause();
    _streamController.add("pause");
    _streamB.add("pause");
  }

  void onCancel() {
    _StreamSubscription.cancel();
    _streamController.add("cancel");
    _streamB.add("cancel");
  }

  void onEnd() {
    _StreamSubscription.resume();
    _streamController.add("resume");
    _streamB.add("resume");
  }
}
